package com.huatai.bi.utils;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huatai.bi.config.XxlJobConfig;
import com.huatai.bi.entity.XxlJobUserEntity;
import com.huatai.bi.service.XxlJobUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.math.BigInteger;


/**
 * @author gusiyi
 * @version 1.0
 * @className XxlJobUtil
 * @description 描述：
 * @date 2024/7/2 20:28
 */
@Configuration
@Slf4j
public class XxlJobUtil {

	@Autowired
	private XxlJobConfig xxlJobConfig;

	@Autowired
	private XxlJobUserService xxlJobUserService;

	/**
	 * 获取登陆后cookie
	 * @return
	 */
	public String login(){
		LambdaQueryWrapper<XxlJobUserEntity> xxlJobUserWrappers =  Wrappers.lambdaQuery();
		xxlJobUserWrappers.eq(XxlJobUserEntity::getUsername,xxlJobConfig.getUsername());
		XxlJobUserEntity xxlJobUser = xxlJobUserService.getOne(xxlJobUserWrappers);
		String tokenJson = writeValueAsString(xxlJobUser);
		String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
		return tokenHex;
	}

	private final static ObjectMapper objectMapper = new ObjectMapper();
	public static ObjectMapper getInstance() {
		return objectMapper;
	}

	public static String writeValueAsString(Object obj) {
		try {
			return getInstance().writeValueAsString(obj);
		} catch (JsonGenerationException e) {
			log.error(e.getMessage(), e);
		} catch (JsonMappingException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
}
